---
interface TabItem {
  title: string;
  content: string;
  id: number;
}

interface Props {
  title?: string;
}

const { title } = Astro.props;

const tabItems: TabItem[] = await Promise.all(
  (await Astro.slots.render('default'))
    .split('</li>')
    .filter((item: string) => item.trim())
    .map(async (item: string, index: number) => {
      const titleMatch = item.match(/button>([^<]+)</);
      let title = titleMatch ? titleMatch[1].trim() : ``;
      title = title || `Tab ${index + 1}`;
      const content = item.replace(/<button>[^<]+<\/button>/, '');
      return {
        title,
        content,
        id: index + 1,
      };
    })
);

// Generate a unique ID for this tabs instance
const tabsId = Math.random().toString(36).substring(2, 9);
---

<div class="bg-white text-gray-800 pb-10 not-prose" data-tabs-container={tabsId}>
  {title && <h2 class="text-2xl font-bold text-gray-800 mb-6">{title}</h2>}

  {/* Tab List */}
  <div class="">
    <nav class="-mb-px flex" aria-label="Tabs">
      {
        tabItems.map((item) => (
          <button
            class="whitespace-nowrap py-4 px-1 border-b-2 px-6 font-bold text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-100 focus:outline-none"
            data-tab={item.id}
            aria-selected="false"
          >
            {item.title}
          </button>
        ))
      }
    </nav>
  </div>

  {/* Tab Panels */}
  <div class="mt-4">
    {
      tabItems.map((item) => (
        <div class="hidden tab-content" data-tab-content={item.id} role="tabpanel">
          <Fragment set:html={item.content} />
        </div>
      ))
    }
  </div>
</div>

<script>
  function initTabs(container: HTMLElement): void {
    const tabs: NodeListOf<HTMLButtonElement> = container.querySelectorAll('[data-tab]');
    const panels: NodeListOf<HTMLElement> = container.querySelectorAll('[data-tab-content]');

    // Show first tab by default
    tabs[0]?.classList.add('text-purple-600', 'border-purple-600');
    tabs[0]?.classList.remove('text-gray-500', 'border-transparent');
    panels[0]?.classList.remove('hidden');

    tabs.forEach((tab: HTMLButtonElement) => {
      tab.addEventListener('click', () => {
        // Remove active states
        tabs.forEach((t: HTMLButtonElement) => {
          t.classList.remove('text-purple-600', 'border-purple-600');
          t.classList.add('text-gray-500', 'border-transparent');
        });
        panels.forEach((p: HTMLElement) => p.classList.add('hidden'));

        // Set active states
        tab.classList.remove('text-gray-500', 'border-transparent');
        tab.classList.add('text-purple-600', 'border-purple-600');

        // Show corresponding panel
        const tabId = tab.getAttribute('data-tab');
        container.querySelector(`[data-tab-content="${tabId}"]`)?.classList.remove('hidden');
      });
    });
  }

  // We use `ViewTransitions`
  // Whenever happens a navigation, from view transitions or native to the browser, init the tabs.
  document.addEventListener('astro:page-load', () => {
    // Initialize all tab containers
    document.querySelectorAll('[data-tabs-container]').forEach((container: Element) => {
      initTabs(container as HTMLElement);
    });
  });
</script>
